<template>
  <view class="container">
    <view class="header">
      <text class="title">忘记密码</text>
      <text class="subtitle">请选择找回方式并按照提示重置密码</text>
    </view>
    
    <view class="form-container">
      <!-- 找回方式选择 -->
      <view class="recovery-methods">
        <view class="method-tab" :class="{ active: recoveryMethod === 'phone' }" @click="recoveryMethod = 'phone'">
          <text class="method-icon">📱</text>  <text class="method-text">手机号找回</text>
        
        </view>
        <view class="method-tab" :class="{ active: recoveryMethod === 'email' }" @click="recoveryMethod = 'email'">
          <text class="method-icon">✉️</text>
          <text class="method-text">邮箱找回</text>
        </view>
      </view>
      
      <!-- 手机号找回表单 -->
      <view class="form-group" v-if="recoveryMethod === 'phone'">
        <text class="label">手机号码</text>
        <input 
          class="input" 
          type="number" 
          placeholder="请输入手机号码" 
          v-model="form.phone"
        />
      </view>
      
      <!-- 邮箱找回表单 -->
      <view class="form-group" v-if="recoveryMethod === 'email'">
        <text class="label">邮箱地址</text>
        <input 
          class="input" 
          type="text" 
          placeholder="请输入邮箱地址" 
          v-model="form.email"
        />
      </view>
      
      <!-- 验证码 -->
      <view class="form-group">
        <text class="label">验证码</text>
        <view class="verification-code-group">
          <input 
            class="input verification-code-input" 
            type="text" 
            placeholder="请输入验证码" 
            v-model="form.verificationCode"
          />
          <button class="send-code-btn" :disabled="countingDown" @click="sendVerificationCode">
            {{ countingDown ? `${countdown}秒后重发` : '发送验证码' }}
          </button>
        </view>
      </view>
      
      <!-- 新密码 -->
      <view class="form-group">
        <text class="label">新密码</text>
        <view class="password-group">
          <input 
            class="input password-input" 
            :type="showNewPassword ? 'text' : 'password'" 
            placeholder="请输入新密码" 
            v-model="form.newPassword"
          />
          <view class="eye-icon" @click="toggleNewPasswordVisibility">
            <text>{{ showNewPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
        <text class="password-hint">密码长度至少8位，包含字母和数字</text>
      </view>
      
      <!-- 确认新密码 -->
      <view class="form-group">
        <text class="label">确认新密码</text>
        <view class="password-group">
          <input 
            class="input password-input" 
            :type="showConfirmPassword ? 'text' : 'password'" 
            placeholder="请再次输入新密码" 
            v-model="form.confirmPassword"
          />
          <view class="eye-icon" @click="toggleConfirmPasswordVisibility">
            <text>{{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}</text>
          </view>
        </view>
      </view>
      
      <!-- 重置密码按钮 -->
      <Button 
        class="reset-btn" 
        type="primary" 
        text="重置密码" 
        :loading="loading"
        @click="handleReset"
      />
      
      <!-- 返回登录链接 -->
      <view class="login-link">
        <text class="link" @click="goToLogin">返回登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { services } from '../../api/index.js';
const userAPI = services.user;

export default {
  data() {
    return {
      recoveryMethod: 'email', // 'phone' 或 'email'
      form: {
        phone: '',
        email: '',
        verificationCode: '',
        newPassword: '',
        confirmPassword: ''
      },
      loading: false,
      showNewPassword: false,
      showConfirmPassword: false,
      countingDown: false,
      countdown: 60
    };
  },
  methods: {
    toggleNewPasswordVisibility() {
      this.showNewPassword = !this.showNewPassword;
    },
    
    toggleConfirmPasswordVisibility() {
      this.showConfirmPassword = !this.showConfirmPassword;
    },
    
    async sendVerificationCode() {
      if (this.recoveryMethod === 'phone') {
        if (!this.form.phone) {
          uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
          });
          return;
        }
        
        // 验证手机号格式
        if (!this.isValidPhone(this.form.phone)) {
          uni.showToast({
            title: '请输入有效的手机号码',
            icon: 'none'
          });
          return;
        }
      } else if (this.recoveryMethod === 'email') {
        if (!this.form.email) {
          uni.showToast({
            title: '请输入邮箱地址',
            icon: 'none'
          });
          return;
        }
        
        // 验证邮箱格式
        if (!this.isValidEmail(this.form.email)) {
          uni.showToast({
            title: '请输入有效的邮箱地址',
            icon: 'none'
          });
          return;
        }
      }
      
      try {
        this.countingDown = true;
        this.countdown = 60;
        if (this.recoveryMethod === 'phone') {
          await userAPI.default.getForgetCode({ areaCode: '86', phone: this.form.phone });
        } else {
          await userAPI.default.getForgetEmailCode({ email: this.form.email });
        }
        const timer = setInterval(() => {
          this.countdown--;
          if (this.countdown <= 0) {
            clearInterval(timer);
            this.countingDown = false;
          }
        }, 1000);
        uni.showToast({ title: '验证码已发送', icon: 'success' });
      } catch (e) {
        this.countingDown = false;
      }
    },
    
    isValidEmail(email) {
      const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
      return emailRegex.test(email);
    },
    
    isValidPhone(phone) {
      // 中国大陆手机号验证规则
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phone);
    },
    
    isValidPassword(password) {
      // 密码长度至少8位，包含字母和数字
      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
      return passwordRegex.test(password);
    },
    
    async handleReset() {
      if (this.recoveryMethod === 'phone') {
        if (!this.form.phone) {
          uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
          });
          return;
        }
        
        // 验证手机号格式
        if (!this.isValidPhone(this.form.phone)) {
          uni.showToast({
            title: '请输入有效的手机号码',
            icon: 'none'
          });
          return;
        }
      } else if (this.recoveryMethod === 'email' && !this.form.email) {
        uni.showToast({
          title: '请输入邮箱地址',
          icon: 'none'
        });
        return;
      }
      
      if (this.recoveryMethod === 'email' && !this.isValidEmail(this.form.email)) {
        uni.showToast({
          title: '请输入有效的邮箱地址',
          icon: 'none'
        });
        return;
      }
      
      if (!this.form.verificationCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
      
      if (!this.form.newPassword) {
        uni.showToast({
          title: '请输入新密码',
          icon: 'none'
        });
        return;
      }
      
      if (!this.isValidPassword(this.form.newPassword)) {
        uni.showToast({
          title: '密码长度至少8位，包含字母和数字',
          icon: 'none'
        });
        return;
      }
      
      if (this.form.newPassword !== this.form.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        });
        return;
      }
      
      try {
        this.loading = true;
        if (this.recoveryMethod === 'phone') {
          await userAPI.forgotPasswordSms({ number: this.form.phone, password: this.form.newPassword, code: this.form.verificationCode });
        } else {
          await userAPI.forgotPasswordEmail({ number: this.form.email, password: this.form.newPassword, code: this.form.verificationCode });
        }
        uni.showToast({ title: '密码重置成功', icon: 'success', duration: 1500 });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/auth/login' });
        }, 1500);
      } finally {
        this.loading = false;
      }
    },
    
    goToLogin() {
      uni.navigateTo({
        url: '/pages/auth/login'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: $spacing-xl;
  background-color: $background-color;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 100rpx;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 60rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: $text-primary;
  display: block;
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  color: $text-secondary;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
}

.recovery-methods {
  display: flex;
  margin-bottom: 40rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  overflow: hidden;
  width: 100%;
}

.method-tab {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  font-size: 24rpx;
  color: $text-secondary;
  margin: 0 10rpx;
}

.method-tab:first-child {
  margin-left: 0;
}

.method-tab:last-child {
  margin-right: 0;
}

.method-tab.active {
  background-color: $primary-color;
  color: #ffffff;
}

.method-icon {
  font-size: 36rpx;
  margin-right: 10rpx;
}

.method-text {
  font-size: 24rpx;
}

.form-group {
  margin-bottom: 32rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: $text-primary;
  margin-bottom: 12rpx;
}

.input {
  width: 100%;
  height: 96rpx;
  padding: 0 32rpx;
  border: 1rpx solid $text-tertiary;
  border-radius: 16rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #ffffff;
}

.verification-code-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.verification-code-input {
  flex: 1;
}

.send-code-btn {
  height: 96rpx;
  padding: 0 32rpx;
  border: 1rpx solid $primary-color;
  border-radius: 16rpx;
  background-color: #ffffff;
  color: $primary-color;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 200rpx;
}

.send-code-btn:disabled {
  opacity: 0.6;
  border-color: $text-tertiary;
  color: $text-tertiary;
}

.password-group {
  position: relative;
}

.password-input {
  padding-right: 80rpx;
}

.eye-icon {
  position: absolute;
  right: 32rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40rpx;
}

.password-hint {
  font-size: 24rpx;
  color: $text-tertiary;
  margin-top: 8rpx;
  display: block;
}

.reset-btn {
  height: 46rpx;
  line-height: 46rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  margin-bottom: 40rpx;
  position: relative;
}

.reset-btn::before {
  content: "🔑";
  margin-right: 8rpx;
}

.login-link {
  text-align: center;
}

.link {
  color: $primary-color;
  font-size: 28rpx;
  
  &:active {
    opacity: 0.8;
  }
}
</style>